package com.cy.store.service.impl;

import com.cy.store.mapper.AddressMapper;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.pojo.Address;
import com.cy.store.pojo.Order;
import com.cy.store.pojo.OrderItem;
import com.cy.store.service.IAddressService;
import com.cy.store.service.ICartService;
import com.cy.store.service.IOrderService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.certpath.OCSPResponse;

import java.util.Date;
import java.util.List;

/**
 * @PROJECT_NAME: store
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/10 14:28
 */
@Service
public class OrderServiceImpl   implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;
    @Override
    public Order create(Integer aid, Integer uid, String username, Integer[] cids) {
        //查询勾选的列表的数据
        List<CartVo> list = cartService.getVOByCid(uid, cids);
        //计算商品的总价
        Long totalPrice = 0l;
        for (CartVo cartVo : list) {
            totalPrice +=   cartVo.getRealPrice()* cartVo.getNum();
        }
        Address address = addressService.getByAid(aid, uid);
        //插入数据
        Order order = new Order();
        order.setUid(uid);
        //收货地址
        order.setRecvPhone(address.getPhone());
        order.setRecvName(address.getName());
        order.setRecvAddress(address.getAddress());
        order.setRecvArea(address.getAreaName());
        order.setRecvCity(address.getCityName());
        order.setRecvProvince(address.getProvinceName());
        //支付 总价
        order.setStatus(0);
        order.setTotalPrice(totalPrice);
        order.setOrderTime(new Date());
        //四个基类属性
        order.setCreatedTime(new Date());
        order.setCreatedUser(username);
        order.setModifiedTime(new Date());
        order.setModifiedUser(username);

        Integer integer = orderMapper.insertOrder(order);
        if (integer !=1 ){
            throw new InsertException("插入时异常");
        }
        for (CartVo cartVo : list) {
            //订单项数据对象
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(cartVo.getPid());
            orderItem.setTitle(cartVo.getTitle());
            orderItem.setPrice(cartVo.getPrice());
            orderItem.setNum(cartVo.getNum());
            orderItem.setCreatedTime(new Date());
            orderItem.setCreatedUser(username);
            orderItem.setModifiedTime(new Date());
            orderItem.setModifiedUser(username);

            Integer integer1 = orderMapper.insertOrderItem(orderItem);
            if (integer != 1) {
                throw  new InsertException("插入时产生了未知的异常");
            }
        }
        return order;
    }
}
